package cn.harry.modular.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.harry.modular.system.domain.SysUserRole;
import cn.harry.modular.system.service.SysUserRoleService;
import cn.harry.modular.system.mapper.SysUserRoleMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author harry
 * @公众号 Harry技术
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole>
        implements SysUserRoleService {
    @Override
    public List<Long> listRoleIdByUserId(Long userId) {
        List<Long> ids = new ArrayList<>();
        List<SysUserRole> sysUserRoles = list(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userId));
        if (CollectionUtil.isNotEmpty(sysUserRoles)) {
            sysUserRoles.forEach(item -> ids.add(item.getRoleId()));
            return ids;
        }
        return null;
    }

    @Override
    public void insertUserAndUserRole(Long userId, List<Long> roleIdList) {
        this.baseMapper.insertUserAndUserRole(userId, roleIdList);
    }

    @Override
    public void rebuildRole(Long userId, List<Long> roleIdList) {
        remove(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userId));
        if (CollUtil.isNotEmpty(roleIdList)) {
            // 保存用户与角色关系
            insertUserAndUserRole(userId, roleIdList);
        }
    }
}




